package org.netty.handler;

import com.sun.xml.internal.bind.v2.model.core.ID;
import com.webside.netty.enums.MsgType;
import com.webside.netty.model.*;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.ReferenceCountUtil;

public class ClientHandler extends SimpleChannelInboundHandler<BaseMsg>{

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if(IdleStateEvent.class.isAssignableFrom(evt.getClass()))
        {
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
            if(idleStateEvent.state() == IdleState.WRITER_IDLE)
            {
                PingMsg pingMsg = new PingMsg();
                ctx.writeAndFlush(pingMsg);
                System.out.println("send ping to server----------");
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, BaseMsg baseMsg) throws Exception {
        MsgType type = baseMsg.getType();
        switch (type)
        {
            case LOGIN:
            {
                LoginMsg loginMsg = new LoginMsg();
                loginMsg.setUserName("wjggwm");
                loginMsg.setPassword("wjggwm");
                channelHandlerContext.writeAndFlush(loginMsg);
            }
            break;
            case PING:
            {
                System.out.println("receive ping from server----------");
            }
            break;
            case REPLY:
            {
                ReplyMsg replyMsg=(ReplyMsg)baseMsg;
                ReplyServerBody replyServerBody=(ReplyServerBody)replyMsg.getBody();
                System.out.println("receive server msg: "+replyServerBody.getServerInfo());
            }
            break;
            case ASK:
            {
                ReplyClientBody replyClientBody=new ReplyClientBody("client info **** !!!");
                ReplyMsg replyMsg=new ReplyMsg();
                replyMsg.setBody(replyClientBody);
                channelHandlerContext.writeAndFlush(replyMsg);
            }
            break;
            default:

                break;
        }
        ReferenceCountUtil.safeRelease(baseMsg);

    }
}
